import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/entity/ClassEntity.dart';
import 'package:thinking/event/ClassEditEvent.dart';
import 'package:thinking/event/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/views/Index/ClassList.dart';
import 'package:thinking/views/Index/Default.dart';
import 'package:thinking/views/Index/EditDiaLog.dart';
import 'package:thinking/views/Index/History.dart';
import 'package:thinking/widget/_.dart';

import 'Country.dart';

class Index extends StatefulWidget {
  final Function clickHead;

  Index({required this.clickHead});

  @override
  _Index createState() => _Index(this.clickHead);
}

class _Index extends State<Index>
    with AutomaticKeepAliveClientMixin<Index>, SingleTickerProviderStateMixin {
  final Function clickHead;
  _Index(this.clickHead);
  late AnimationController _animationController;
  late Animation<double> _animationA;
  late Animation<double> _animationB;
  late Animation<double> _animationC;
  bool canDown = true;
  bool canUp = false;
  @override
  bool get wantKeepAlive => true;
  double lastPixes = 0;

  String userHeadImg = SPreferences().getString('user_HeadImg');
  ClassResult tabs = ClassResult.fromJson({'principal': [], 'additional': []});
  int index = 0;

  @override
  void initState() {
    super.initState();
    _editOnListen();
    _getClassData();
    _animationController =
        AnimationController(duration: Duration(milliseconds: 300), vsync: this);

    _animationA = Tween(begin: 1.0, end: 0.4).animate(_animationController);
    _animationB = Tween(begin: 1.0, end: 0.5).animate(_animationController);
    _animationC = Tween(begin: 1.0, end: 0.0).animate(_animationController);
  }

  Future<void> _editOnListen() async {
    Config.eventBus.on<ClassEditEvent>().listen((event) {
      if (event.update) {
        index = 0;
        tabs = ClassResult.fromJson({'principal': [], 'additional': []});
        _getClassData();
      }
    });
  }

  Future<void> _getClassData() async {
    tabs = (await HomeService.getClassData())!;
    setState(() {});
  }

  @override
  void dispose() {
    super.dispose();
  }

  PreferredSize titleWidget() {
    return PreferredSize(
        preferredSize: Size.fromHeight(Screen.setHeight(70 + Config.top)),
        child: Container(
          decoration: BoxDecoration(color: ColorConfig.ThemeColor, boxShadow: [
            BoxShadow(
              color: ColorConfig.BlackObsBackColor,
              blurRadius: 2,
              spreadRadius: 0.5,
            )
          ]),
          padding: EdgeInsets.only(top: Screen.setHeight(Config.top)),
          width: Screen.width(context),
          child: SizeTransition(
            axis: Axis.vertical,
            sizeFactor: _animationB,
            child: Column(
              children: [
                title(),
                bottom(),
              ],
            ),
          ),
        ));
  }

  Widget title() {
    return Container(
        padding: EdgeInsets.only(top: 5),
        width: Screen.width(context),
        child: SizeTransition(
          axis: Axis.vertical,
          sizeFactor: _animationA,
          child: FadeTransition(
            opacity: _animationC,
            child: Row(
              children: <Widget>[
                Container(
                  constraints: BoxConstraints(
                      maxHeight: Screen.setWidth(38),
                      maxWidth: Screen.setWidth(38)),
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.all(Radius.circular(19)),
                      boxShadow: [
                        BoxShadow(
                            color: ColorConfig.ThemeOtherColor,
                            offset: Offset(1, 1),
                            blurRadius: 1,
                            spreadRadius: 0)
                      ]),
                  margin: EdgeInsets.only(left: 10),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(30),
                    child: ClipOval(
                      child: Image.network(
                        userHeadImg,
                        height: Screen.setWidth(38),
                        width: Screen.setWidth(38),
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child: GestureDetector(
                    onTap: () {
                      Modular.to.pushNamed('/indexSearch/0');
                    },
                    child: Panel(
                      top: 0,
                      bottom: 0,
                      child: const ShowSearchWidget(),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  Panel bottom() {
    return Panel(
        top: 0,
        bottom: 0,
        left: 0,
        right: 5,
        child: Container(
            width: Screen.width(context),
            child: Row(
              children: [
                Expanded(
                    child: TabBar(
                  tabs: tabs.principal!
                      .asMap()
                      .keys
                      .map((e) => Tab(
                            child: Padding(
                              padding: EdgeInsets.only(top: 6, bottom: 6),
                              child: Text(
                                tabs.principal![e].title!,
                              ),
                            ),
                          ))
                      .toList(),
                  isScrollable: true,
                  labelColor: ColorConfig.WhiteBackColor,
                  unselectedLabelColor: Color(0xB2FFFFF0),
                  indicatorWeight: 2,
                  indicatorColor: ColorConfig.WhiteBackColor,
                  indicatorSize: TabBarIndicatorSize.tab,
                  onTap: (int i) {},
                )),
                Container(
                    child: GestureDetector(
                  child: Icon(
                    Icons.edit,
                    color: ColorConfig.NoActiveColor,
                    size: Screen.setFontSize(20.0),
                  ),
                  onTap: () {
                    showEditDialog();
                  },
                ))
              ],
            )));
  }

  List<Widget> tabView() {
    return tabs.principal!
        .map((e) => e.id == 1
            ? DefaultLayout()
            : e.id == 4
                ? History()
                : e.id == 3
                    ? Country()
                    : e.id == 5
                        ? ClassList(classValue: '分画作')
                        : e.id == 6
                            ? ClassList(classValue: '分古籍')
                            : Center(
                                child: Text(e.id.toString()),
                              ))
        .toList();
  }

  showEditDialog() {
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return EditDiaLog();
        });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return DefaultTabController(
        initialIndex: index,
        length: tabs.principal!.length != 0 ? tabs.principal!.length : 0,
        child: Scaffold(
          appBar: titleWidget(),
          body: Container(
              child: NotificationListener<ScrollNotification>(
            onNotification: (ScrollNotification notification) {
            if(!notification.metrics.outOfRange){
              if (notification.metrics.axis == Axis.vertical) {
                if (notification.metrics.pixels - lastPixes>0.3 && canDown ) {
                  if (_animationController.status ==
                      AnimationStatus.dismissed) {
                    _animationController.forward();
                    setState(() {
                      canDown = false;
                      canUp = true;
                    });
                  }
                }
                if (notification.metrics.pixels - lastPixes<-0.3 && canUp ) {
                  if (_animationController.status ==
                      AnimationStatus.completed) {
                    _animationController.reverse();
                    setState(() {
                      canDown = true;
                      canUp = false;
                    });
                  }
                }
                  lastPixes = notification.metrics.pixels;

              }
              if( notification.metrics.pixels<20000&&notification.metrics.axis == Axis.horizontal){
                lastPixes = 0;
              }
            }
              return true;
            },
            child: TabBarView(
              children: tabView(),
            ),
          )),
        ));
  }
}
